import request from '@/plugins/request';
import renderUrl from '@/api/apiHost';
import CryptoJS from "crypto-js";
import cookies from "@/libs/util.cookies.js";

//通用下拉框接口
export const getDicDataByCode = (sortCode, sortid = "") => {
  return request({
    url: renderUrl("utiltools")+"/support/bcode/listBCodesBySortIdOrSortCode",
    method: "get",
    params: {
      sortCode,
      sortid
   }
})
}

//将下拉框接口循环替换成label，value值
export const initDicData = (arr) => {
  if (arr) {
    return arr.map(item => {
      return {
        label: item.codeName,
        value: item.codeValue
      }
    })
  }

}
/**
 *
 * @param {*} url
 */
export const fetchFile = (url) => {
  return fetch(
     renderUrl("utiltools") +
       "/support/file/download?fileUrl=" +
       url,
     {
       method: "get",
       headers: {
         "Content-type": "application/json",
         Authorization: cookies.get("access_token")
       }
     }
   )
     .then(response => response.blob())
 }

 //年月日 开始时间结束时间
export const getDateObject = () => {
  const date = new Date()
  let Y = date.getFullYear()
  let M = Number(date.getMonth()) + 1
  let D = date.getDate()
  let beginTime = Y + '-' + (M < 10 ? '0' + M : M) + '-01'
  let endTime = Y + '-' + (M < 10 ? '0' + M : M) + '-' + (D < 10 ? '0' + D : D)
  return { beginTime, endTime }
}


/**
* 根据两个日期，判断相差天数
* @param sDate1 开始日期 如：2016-11-01
* @param sDate2 结束日期 如：2016-11-02
* @returns {number} 返回相差天数
*/
export const daysBetween = (sDate1,sDate2)=>{
//Date.parse() 解析一个日期时间字符串，并返回1970/1/1 午夜距离该日期时间的毫秒数
  var time1 = Date.parse(new Date(sDate1));
  var time2 = Date.parse(new Date(sDate2));
  var nDays = Math.abs(parseInt((time2 - time1)/1000/3600/24));
  return nDays;
}

/**
 * 中国标准时间格式化
 */
export const crtTimeFtt = (date, type) => {
  if (date === null || date === '') {
    return date;
  }
  var d = new Date(date);
  var year = d.getFullYear();
  var month = d.getMonth() + 1;
  if (month < 10) {
    month = "0" + month;
  }
  var day = d.getDate();
  if (day < 10) {
    day = "0" + day;
  }
  var hours = d.getHours();
  if (hours < 10) {
    hours = "0" + hours;
  }
  var min = d.getMinutes();
  if (min < 10) {
    min = "0" + min;
  }
  var ss = d.getSeconds();
  if (ss < 10) {
    ss = "0" + ss;
  }
  if (type === 'yyyy-MM-dd') {
    var youWant =
      year + "-" + month + "-" + day;
  } else if (type === 'yyyyMMdd') {
    var youWant =
      year + "" + month + "" + day;
  } else if (type === 'yyyy-MM') {
    var youWant =
      year + "-" + month;
  } else if (type === 'yyyyMM') {
    var youWant =
      year + "" + month;
  } else {
    var youWant =
      year + "-" + month + "-" + day;
  }
  return youWant;
}
/**
 *
 * @description 第一个参数为需要转换的日期 第二个参数为转换成的时间格式如 yyyy-MM-dd hh:mm yyyy.MM.dd hh:mm:ss
 */
export const formatDate = (date, fmt) => {
  var date = new Date(date)
  var o = {
    "M+": date.getMonth() + 1, // 月份
    "d+": date.getDate(), // 日
    "h+": date.getHours(), // 小时
    "m+": date.getMinutes(), // 分
    "s+": date.getSeconds(), // 秒
    "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
    "S": date.getMilliseconds()
    // 毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "")
      .substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) :
        (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

/**
 * [通过参数名获取url中的参数值]
 * 示例URL:http://htmlJsTest/getrequest.html?uid=admin&rid=1&fid=2&name=小明
 * @param  {[string]} queryName [参数名]
 * @return {[string]}           [参数值]
 */
export function GetQueryValue(queryName) {
  var query = decodeURI(window.location.search.substring(1));
  var vars = query.split("&");
  for (var i = 0; i < vars.length; i++) {
      var pair = vars[i].split("=");
      if (pair[0] == queryName) { return pair[1]; }
  }
  return null;
}

export function render(itemColumnCode) {
  return (h, params) => {
    if (params.row[itemColumnCode]) {
      let numberAndEnglish = String(params.row[itemColumnCode]).replace(/[^0-9][a-z][A-Z]+/g, ''); //正则获取字符串包含数组和大小写英文字母的内容
      let ChineseLength = String(params.row[itemColumnCode]).replace(/[^\u4e00-\u9fa5]+/g, ''); //正则获取字符串包含汉字的内容
      let paramsRowItemColumnCode = numberAndEnglish.length * 8 + ChineseLength.length * 12;
      let paramsRowItemColumnContent = params.row[itemColumnCode];
      if (params.row[itemColumnCode].indexOf(" ") !== -1) { //如果内容存在空格

        //使用正则吧空格替换为span包裹的&nbsp（因为多个空格浏览器只显示一个空格）
        paramsRowItemColumnContent = params.row[itemColumnCode].replace(/\s/g, '<span>&nbsp;</span>');
      }
      if ((params.column._width * 0.9 < paramsRowItemColumnCode)) {
        return h('div', [
          h('Tooltip', {
            props: {
              placement: 'bottom'
            },
            transfer: true
          }, [
            h('span', {
              style: { //如果内容超出span标签的具体宽度，超出部分显示省略号
                display: 'inline-block',
                width: params.column._width * 0.9 + 'px',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
              },
              domProps: { //向iview的dom的Props设置innerHTML用来渲染标签，iview的新版本只能渲染字符串
                innerHTML: paramsRowItemColumnContent
              }
            }),
            h('span', {
              slot: 'content',
              style: {
                whiteSpace: 'normal',
                wordBreak: 'break-all'
              },
              domProps: {
                innerHTML: paramsRowItemColumnContent
              }
            }, )
          ])
        ])
      } else {
        return h('div', [
          h('span', {
            domProps: {
              innerHTML: paramsRowItemColumnContent
            }
          })
        ])
      }
    }
  }
}

/**
 * 查找子节点的父节点及祖先节点
 */
export function findAllParent (node, tree, parentNodes = [], index = 0) {
  if (!node || node.fid=== 0) {
    return
  }
  findParent(node, parentNodes, tree)
  let parentNode = parentNodes[index]
  findAllParent(parentNode, tree, parentNodes, ++index)
  return parentNodes
}

function findParent (node, parentNodes, tree) {
  for (let i = 0; i < tree.length; i++) {
    let item = tree[i]
    if (item.id === node.fid) {
      console.log(1111)
      parentNodes.push(item)
      return
    }
    if (item.children && item.children.length > 0) {
      findParent(node, parentNodes, item.children)
    }
  }
}


//根据年月得到天数
export function getDayNumByYearMonth (year,month){
  switch (month) {
      case 1:
      case 3:
      case 5:
      case 7:
      case 8:
      case 10:
      case 12:
          return 31;
          break;
      case 4:
      case 6:
      case 9:
      case 11:
          return 30;
          break;
      case 2:
          isLeapYear(year) ? 29 : 28;
  }
}
//是否是闰年
 function isLeapYear (year){
  if(year/4 == 0 && year/100 != 0){
      return true ;
  } else if (year/400 == 0){
      return true ;
  } else{
      return false ;
  }
}
/**
 * 密码 手机号码加密
 */
export const setPwd = (pwd)=>{
  return CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(pwd), CryptoJS.enc.Utf8.parse("c9d2eea8faea11e996ed14ecd17545c4"), {
    mode: CryptoJS.mode.ECB
  }).toString();
}
//动态加载百度地图
export function LoadBaiduMapScript() {
  //console.log("初始化百度地图脚本...");
   //加载样式
  //  const $link = document.createElement("link");
  //  $link.type = "text/css";
  //  $link.href = "//10.223.32.190:20024/baidumap/bmapgl/api/bmap.css";
  //  document.head.appendChild($link);
  // const BMap_URL = "//10.223.32.190:20024/bmapgl/?qt=getscript&libraries=visualization";
  const AK = "yewN169efpKa3N5LWWKkcCal1FfmmtcG"; //本地百度地图专用地址
  const BMap_URL = "https://api.map.baidu.com/api?v=3.0&ak="+ AK +"&s=1&callback=onBMapCallback"; //本地百度地图专用地址
  // const BMap_URL = "https://zhny.hn.sgcc.com.cn:20019/baidumap/jsapi/api.js"; //打包百度地图专用地址
  return new Promise((resolve, reject) => {
      // 如果已加载直接返回
      if(typeof BMap !== "undefined") {
          resolve(BMap);
          return true;
      }
      // 百度地图异步加载回调处理
      window.onBMapCallback = function () {
          resolve(BMap);
      };
      // 插入script脚本
      let scriptNode = document.createElement("script");
      scriptNode.setAttribute("type", "text/javascript");
      scriptNode.setAttribute("src", BMap_URL);
      document.body.appendChild(scriptNode);
  });
}
export const bMapStyle = [{
  "featureType": "land",
  "elementType": "geometry",
  "stylers": {
      "color": "#fffff9ff"
  }
}, {
  "featureType": "green",
  "elementType": "geometry",
  "stylers": {
      "color": "#cceac8ff"
  }
}, {
  "featureType": "subwaystation",
  "elementType": "geometry",
  "stylers": {
      "visibility": "on",
      "color": "#9b9b9bff"
  }
}, {
  "featureType": "transportation",
  "elementType": "geometry",
  "stylers": {
      "color": "#9b9b9bff"
  }
}, {
  "featureType": "transportation",
  "elementType": "labels",
  "stylers": {
      "visibility": "on"
  }
}, {
  "featureType": "transportation",
  "elementType": "labels.text.fill",
  "stylers": {
      "color": "#4a4a4aff"
  }
}, {
  "featureType": "road",
  "elementType": "geometry.fill",
  "stylers": {
      "color": "#ffffffff"
  }
}, {
  "featureType": "subway",
  "elementType": "geometry.fill",
  "stylers": {
      "color": "#9b9b9bff"
  }
}, {
  "featureType": "districtlabel",
  "elementType": "labels.text.fill",
  "stylers": {
      "color": "#9b9b9bff"
  }
}, {
  "featureType": "water",
  "elementType": "labels.text.fill",
  "stylers": {
      "color": "#69b0acff"
  }
}, {
  "featureType": "manmade",
  "elementType": "labels.text.fill",
  "stylers": {
      "color": "#4a4a4aff"
  }
}, {
  "featureType": "manmade",
  "elementType": "labels.text.stroke",
  "stylers": {
      "color": "#ffffff00"
  }
}, {
  "featureType": "education",
  "elementType": "labels.text.fill",
  "stylers": {
      "color": "#4a4a4aff"
  }
}, {
  "featureType": "poilabel",
  "elementType": "labels",
  "stylers": {
      "visibility": "off"
  }
}, {
  "featureType": "poilabel",
  "elementType": "labels.icon",
  "stylers": {
      "visibility": "off"
  }
}, {
  "featureType": "road",
  "elementType": "labels.text.fill",
  "stylers": {
      "color": "#4a4a4aff"
  }
}, {
  "featureType": "road",
  "elementType": "labels.text.stroke",
  "stylers": {
      "color": "#ffffff00"
  }
}, {
  "featureType": "road",
  "elementType": "geometry",
  "stylers": {
      "visibility": "on"
  }
}, {
  "featureType": "road",
  "elementType": "labels",
  "stylers": {
      "visibility": "on"
  }
}, {
  "featureType": "districtlabel",
  "elementType": "labels",
  "stylers": {
      "visibility": "on"
  }
}, {
  "featureType": "districtlabel",
  "elementType": "labels.icon",
  "stylers": {
      "visibility": "off"
  }
}, {
  "featureType": "provincialway",
  "elementType": "geometry",
  "stylers": {
      "visibility": "on"
  }
}, {
  "featureType": "provincialway",
  "elementType": "labels",
  "stylers": {
      "visibility": "on"
  }
}, {
  "featureType": "provincialway",
  "elementType": "geometry.fill",
  "stylers": {
      "color": "#ffffffff"
  }
}, {
  "featureType": "provincialway",
  "elementType": "geometry.stroke",
  "stylers": {
      "color": "#ffffffff"
  }
}, {
  "featureType": "provincialway",
  "elementType": "labels.text.fill",
  "stylers": {
      "color": "#ffffffff"
  }
}, {
  "featureType": "highwaysign",
  "elementType": "labels",
  "stylers": {
      "visibility": "off"
  }
}, {
  "featureType": "highwaysign",
  "elementType": "labels.icon",
  "stylers": {
      "visibility": "off"
  }
}, {
  "featureType": "nationalwaysign",
  "elementType": "labels",
  "stylers": {
      "visibility": "off"
  }
}, {
  "featureType": "nationalwaysign",
  "elementType": "labels.icon",
  "stylers": {
      "visibility": "off"
  }
}, {
  "featureType": "provincialwaysign",
  "elementType": "labels.icon",
  "stylers": {
      "visibility": "off"
  }
}, {
  "featureType": "provincialwaysign",
  "elementType": "labels",
  "stylers": {
      "visibility": "off"
  }
}, {
  "featureType": "tertiarywaysign",
  "elementType": "labels",
  "stylers": {
      "visibility": "off"
  }
}, {
  "featureType": "tertiarywaysign",
  "elementType": "labels.icon",
  "stylers": {
      "visibility": "off"
  }
}, {
  "featureType": "subwaylabel",
  "elementType": "labels",
  "stylers": {
      "visibility": "off"
  }
}, {
  "featureType": "subwaylabel",
  "elementType": "labels.icon",
  "stylers": {
      "visibility": "off"
  }
}, {
  "featureType": "water",
  "elementType": "geometry",
  "stylers": {
      "color": "#69b0acff"
  }
}, {
  "featureType": "highway",
  "elementType": "geometry.fill",
  "stylers": {
      "color": "#b5caa0ff"
  }
}, {
  "featureType": "scenicspots",
  "elementType": "labels.text.fill",
  "stylers": {
      "color": "#7d9fa0ff"
  }
}, {
  "featureType": "village",
  "elementType": "labels.text.fill",
  "stylers": {
      "color": "#a8b4b2ff"
  }
}, {
  "featureType": "town",
  "elementType": "labels.text.fill",
  "stylers": {
      "color": "#a8b4b2ff"
  }
}]

